<template>
  <CommonPage show-footer title="出诊安排">
    
    <!-- <div style="width: 200px;">
      <n-tree-select
      :options="departments"
      label-field="dept_name"
      key-field="id"
      children-field="children"
      @update:value="handleUpdateValue"
      placeholder="请选择科室："
      />
    </div> -->
    <div v-if="cardVisible" style="text-align: center; ">请选择科室</div>
    <div class="course-week" v-if="!cardVisible">
      <div class="week-top">
        <div class="btn_wrap">
          
          <el-tooltip class="item" effect="dark" content="上周" placement="top">
            <span @click="getLastWeek">
              <i class="el-icon-d-arrow-left"></i>
              上周
            </span>
          </el-tooltip>
          <span @click="getCurWeek">本周</span>
          <el-tooltip class="item" effect="dark" content="下周" placement="top">
            <span @click="getNextWeek">
              下周
              <i class="el-icon-d-arrow-right"></i>
            </span>
          </el-tooltip>
        </div>
        <span class="todayDate">{{ todayDate }}</span>
        <div class="chooseMonth">
          <div>
            <span class="is_expired square"></span>
            <span class="title">已过期</span>
          </div>
          <div>
            <span class="in_progress square"></span>
            <span class="title">进行中</span>
          </div>
          <div>
            <span class="has_not_started square"></span>
            <span class="title">未开始</span>
          </div>
          
        </div>
      </div>
      <div class="week_table">
        <div class="table_header">
          <div class="table_week">
            <template v-for="(item, index) of weeks">
              <span v-if="index === 0" :key="index" class="first">
                {{ item }}
                <i class="el-icon-edit"></i>
              </span>
              <span v-else :key="id">{{ item }}</span>
            </template>
          </div>
          <div class="table_date">
            <template v-for="(item, index) of months">
              <span v-if="index === 0" :key="index" class="first"></span>
              <span v-else :key="id">
                <span class="day_item" :class="{ isCurDate: item && item.isCurDate }">
  {{ item && item.isCurDate ? (item && item.showDate + '(今天)') || '' : (item && item.showDate) || '' }}
</span>
              </span>
            </template>
          </div>
        </div>
        <div class="timePeriodList">
          <ul class="timePeriod_row">
            <!--循环时段，看时段有多少个-->
            <template v-if="schedule.length > 0">
              <li
                v-for="(period, p_index) in schedule"
                :key="'period' + p_index"
                class="timePeriod_col"
              >
                <!--第一列显示时段-->
                <div class="timePeriod">{{ period.doctor.nickname }}</div>
                <!-- 后面显示周一到周日的计划-->
                <div class="row_day">
                  <!-- 循环显示每周的日期-->
                  <template v-for="(month, m_index) of months">
                    <!-- v-if="month" 去除数据处理的时候移除数组第一个为empty的问题-->
                    <div v-if="month" :key="'month'+m_index" class="things" @click="addSchedule(p_index,m_index)">
                      <!-- 循环每个时间段的计划-->
                      <template v-for="(thing, t_index) of period.schedules">
                        <!-- 根据日期和计划的日期匹配 显示 然后根据状态显示进行中 已过期 未开始-->
                        <div
                          v-if="thing.schedule.week === m_index%7"
                          :key="'thing'+t_index"
                          class="thing_item"
                          :class="{ outdated: thing.ticket_status == 0 , waiting: thing.ticket_status == 2 }"
                          @click="handleDetail(thing)"
                          style="width: 100%"
                        >
<!--                          <span>医生：{{ thing.doctor }}</span>-->
                          <span>时间：{{ thing.schedule.time }}</span>
                          <span>价格：￥{{ thing.schedule.price }}</span>
                          <span>剩余：{{ thing.ticket.num }}</span>
                        </div>
                      </template>
                    </div>
                  </template>
                </div>
              </li>
            </template>
            <div v-else class="noMore"><span>暂无数据</span></div>
          </ul>
        </div>
      </div>
    </div>

    <n-modal v-model:show="scheduleVisible">
      <n-card style="width: 500px" size="huge" role="dialog" aria-modal="true">
        <div v-if="selectSch.sche.length > 0">
          <div v-for="(sche, s_index) of selectSch.sche">
            <div class="schedule" >
              <div>
                <div>日期: {{ selectDay.date }}</div>
                <div>时间：{{ sche.schedule.time }}</div>
                <div>价格：￥{{ sche.schedule.price }}$</div>
                <div>余号：{{ sche.ticket.num }}   </div>
              </div>
              <div style="display: flex; justify-content: space-around;">
                <n-button type="info" size="tiny" style="margin: 5px 10px;" @click="handleAddTicketClick(sche.schedule, sche.ticket)">增加号数</n-button>
                <n-button type="warning" size="tiny" style="margin: 5px 10px;" @click="handleAddScheduleClick(sche.schedule)">修改排班</n-button>
                <n-button type="error" size="tiny" style="margin: 5px 10px;" @click="handleDelete">删除排班</n-button>
              </div>
            </div>
            <div v-if="selectSch.sche.length < 2" class="toA" @click="handleAddScheduleClick">
              +点击添加排班
            </div>
          </div>
        </div>
        <div v-if="selectSch.sche.length == 0" class="toA" @click="handleAddScheduleClick">
          +点击添加排班
        </div>
      </n-card>
    </n-modal>


    <!-- 新增/编辑/查看 -->
    <CrudModal
      v-model:visible="addScheduleV"
      :title="title"
      @on-save="handleScheduleSave"
    >
      <n-form
        ref="newSchedule"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="newSchedule"
      >
       
        <n-form-item
          label="星期"
          path="week"
        >
          <n-select disabled="newSchedule.id == null"
            v-model:value="newSchedule.week"
            :options="options"
            @update:value="handleUpdateWeekSelectValue"
          ></n-select>
        </n-form-item>

        <n-form-item
          label="医生"
          path="doctor_id"
        >
          <n-select disabled="newSchedule.id == null"
            v-model:value="newSchedule.doctorView"
            :options="doctorlist"
            @update:value="handleUpdateDoctorSelectValue"
          ></n-select>
        </n-form-item>

        <p style="color: red; text-align: center;"  v-if="errors.length > 0">{{ errors }}</p>
        <n-form-item
          label="价格"
          path="price"
        >
                  <n-input  round placeholder="请输入价格" :allow-input="onlyAllowNumber" v-model:value="newSchedule.price">
                    <template #suffix>
                      元
                    </template>
                  </n-input>
        </n-form-item>
        
        <n-form-item
          label="时间"
          path="time"
        >
          <n-select
            v-model:value="newSchedule.time"
            :options="day"
          ></n-select>
        </n-form-item>

      </n-form>
      
    </CrudModal>


        <!-- 新增/编辑/查看 -->
        <CrudModal
      v-model:visible="addTicketV"
      :title="title"
      @on-save="handleTicketSave"
    >
      <n-form
        ref="newSchedule"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="newSchedule"
      >
        <n-form-item
            label="日期"
            path="price"
          >
                    <n-input  v-model:value="newTicket.day" disabled></n-input>
        </n-form-item>
        <n-form-item
            label="时间"
            path="price"
          >
                    <n-input  v-model:value="newTicket.schedule.day" disabled></n-input>
        </n-form-item>
        <n-form-item
            label="价格"
            path="price"
          >
                    <n-input  v-model:value="newTicket.schedule.price" disabled><template #suffix>
                        元
                      </template></n-input>
        </n-form-item>
        
        <p style="color: red; text-align: center;"  v-if="errors.length > 0">{{ errors }}</p>
        <n-form-item
            label="剩余号数"
            path="price"
          >
                    <n-input  round placeholder="请输入号数" :allow-input="onlyAllowNumber" v-model:value="newTicket.num">
                      <template #suffix>
                        人
                      </template>
                    </n-input>
        </n-form-item>

      </n-form>
      
    </CrudModal>
  </CommonPage>
</template>

<script>
import MyTools from '../../../utils/common/MyTools'
import api from './api'
export default {
  name: 'Arrange',
  data() {
    return {
      errors: "",
      departments: [],
      cardVisible: false,
      scheduleVisible: false,
      addScheduleVisible: false,
      addScheduleV: false,
      title: "",
      addTicketV: false,
      deptId: 0,
      schedule: [],
      modalFormRef: null,
      selectSch: {},
      selectDay: {},
      selectDoctor: {},
      newSchedule: {
        price: 10,
        time: "上午"
      },
      newTicket:{},
      mIndex: 0,
      deptName: "",
      weeks: ['医生', '周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      options: [
      {
        label: "周一",
        value: 1,
        },
        {
        label: "周二",
        value: 2,
      },{
        label: "周三",
        value: 3,
      },{
        label: "周四",
        value: 4,
      },{
        label: "周五",
        value: 5,
      },{
        label: "周六",
        value: 6,
      },{
        label: "周日",
        value: 0,
        }],
      day: [
      {
        label: "上午",
        value: "上午",
        },{
        label: "下午",
        value: "下午",
        }
      ],
      doctorlist:[],
      todayDate: '',
      months: [],
      curDate: '',
      nowDate: new Date(),
      showCourseDetail: false,
    }
  },
  async mounted() {
    this.getCurWeek()
    const res = await api.getAllDepartments()
    for (let i = 0; i < res.data.length; i++){
      res.data[i].disabled=true
    }
    this.departments = res.data
    if (res.data.length == 1) {
      this.cardVisible = true
      // this.deptId = res.data[0].c
    }
    const user = await api.getUser()
    const { department_id } = user.data
    this.deptId = department_id
    this.handleUpdateValue()
    console.log(this.departments)
  },
  methods: {
    handleDelete () {
      $dialog.confirm({
        content: '确认删除？',
        confirm() {
          $message.success('删除成功')
        },
        cancel() {
          $message.warning('已取消')
        },
      })
    },
    async handleScheduleSave() {
      console.log(this.newSchedule)
      this.newSchedule.price = Number(this.newSchedule.price)
      if (this.newSchedule.price <= 0) {
        this.errors = "请输入价格！"
        return
      }
      this.errors = ""
      const res = await api.addSchedule(this.newSchedule)
      if (res.code == 0) {
        $message.success("添加成功")
      }
      let data = {
        dept: this.deptId,
        date: this.months[1].date
      }
      const res2 = await api.getScheduleListByDept(data)
      this.schedule = res2.data
      this.addScheduleV = false
    },
    async handleTicketSave() {
      console.log(this.newTicket)
      if (this.newTicket.num == null) {
        this.errors = "请输入正确可预约人数！"
        return
      }
      this.newTicket.num = Number(this.newTicket.num)
      if (this.newTicket.num == NaN ||this.newTicket.num <= 0) {
        this.errors = "请输入正确可预约人数！"
        return
      }
      this.errors = ""
      const res = await api.addTicket(this.newTicket)
      if (res.code == 0) {
        $message.success("添加成功")
      }
      let data = {
        dept: this.deptId,
        date: this.months[1].date
      }
      const res2 = await api.getScheduleListByDept(data)
      this.schedule = res2.data
      this.addTicketV = false
    },
    handleAddScheduleClick(schedule) {
      this.title = "添加排班"
      this.errors = ""
      if (schedule.id == null) {
        this.newSchedule.price = "10"
        this.newSchedule.time = "上午"
      } else {
        this.newSchedule.id = schedule.id
        this.newSchedule.price = schedule.price
        this.newSchedule.time = schedule.time
        this.title = "修改排班"
      }

      this.newSchedule.doctorView = this.selectSch.doctor.nickname
      this.newSchedule.weekView = this.weeks[this.mIndex]
      this.newSchedule.week = this.mIndex % 7
      this.newSchedule.doctor_id = this.selectSch.doctor.id
      this.newSchedule.department_id = this.deptId
      this.addScheduleVisible = true
      this.addScheduleV = true
    },
    handleAddTicketClick(schedule,ticket) {
      this.title = "添加号数"
      this.errors = ""
      this.newTicket = ticket
      this.newTicket.schedule = schedule
      this.newTicket.schedule_id = schedule.id
      this.newTicket.day = this.months[this.mIndex].date
      
      console.log(this.newTicket)
      this.addTicketV = true
    },

    handleUpdateWeekSelectValue(string, SelectOption) {
      this.newSchedule.weekView = SelectOption.label
      this.newSchedule.week = SelectOption.value
    },
    handleUpdateDoctorSelectValue(string, SelectOption) {
      this.newSchedule.doctorView = SelectOption.label
      this.newSchedule.doctor_id = SelectOption.value
    },
   
    onlyAllowNumber: (value) => !value || /^\d+$/.test(value),
    addNewSchedule() {
      this.addScheduleVisible = false;
      this.addScheduleV = false
    },
    addSchedule(p_index, m_index) {
      this.mIndex = m_index
      this.selectSch = this.schedule[p_index]
      this.selectDay = this.months[m_index]
      console.log(this.selectSch)
      this.scheduleVisible = true
      let schedules = []
      for (let i = 0; i < this.selectSch.schedules.length; i++){
        if (this.selectSch.schedules[i].schedule.week == m_index % 7) {
          schedules.push(this.selectSch.schedules[i])
        }
      }
      this.selectSch.sche = schedules
    },
    sle() {
      this.cardVisible = true
    },
    async handleUpdateValue() {
      let data = {
        dept: this.deptId,
        date: this.months[1].date
      }
      const res = await api.getScheduleListByDept(data)
      this.schedule = res.data
      this.cardVisible = false
      console.log(this.schedule)
      for (let i = 0; i < this.schedule.length; i++){
        this.doctorlist.push({
          label: this.schedule[i].doctor.nickname,
          value:this.schedule[i].doctor.id
        })
      }
      console.log("======")
      console.log(this.doctorlist)
    },
    /**
     * 获取 时间
     * @param time
     */
    getWeek(time) {
      const week = time.getDay() - 1
      time = this.addDate(time, week * -1)
      this.curDate = new Date(time)
      for (let i = 0; i < 7; i++) {
        const { year, month, day } = this.formatDate(i === 0 ? time : this.addDate(time, 1))
        this.months.push({
          date: year + '-' + month + '-' + day,
          showDate: month + '-' + day,
        });
      }
      delete this.months[0]
      this.todayDate = this.months[1].date + ' ~ ' + this.months[this.months.length - 1].date;
    },
    /**
     * 处理日期
     * @param date
     * @param n
     * @returns {*}
     */
    addDate(date, n) {
      date.setDate(date.getDate() + n)
      return date
    },
    // 日期格式处理
    formatDate(date) {
      var year = date.getFullYear()
      var months = date.getMonth() + 1
      var month = (months < 10 ? '0' + months : months).toString()
      var day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()).toString()
      return {
        year,
        month,
        day,
      }
    },
    /**
     * 上周
     */
    async getLastWeek() {
      this.dealDate(this.addDate(this.curDate, -7))
      let data = {
        dept: this.deptId,
        date: this.months[1].date
      }
      const res = await api.getScheduleListByDept(data)
      this.schedule = res.data
    },
    /**
     * 本周
     */
    async getCurWeek() {
      this.dealDate(new Date())
      if (this.deptId != 0) {
        let data = {
          dept: this.deptId,
          date: this.months[1].date
        }
        const res = await api.getScheduleListByDept(data)
        this.schedule = res.data
      }
    },
    /**
     * 下周
     */
    async getNextWeek() {
      this.dealDate(this.addDate(this.curDate, 7))
      let data = {
        dept: this.deptId,
        date: this.months[1].date
      }
      const res = await api.getScheduleListByDept(data)
      this.schedule = res.data
    },
    /**
     * 显示当天日期状态
     * @param date
     */
    dealDate(date) {
      this.months = ['']
      this.getWeek(date)
      const curDate = MyTools.getCurDay()
      this.months.forEach((item) => {
        item.isCurDate = item.date === curDate
      })
    },
    /**
     * 点击查看详情
     * @param row
     */
    handleDetail(row) {
      this.showCourseDetail = true
    },
  },
}
</script>

<style scoped lang="scss">



.toA {
  cursor: pointer; color: blue;
}
.schedule {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-sizing: border-box;
    background-color: #d6e5fd;
    border-radius: 10px;
    margin: 10px;
}

.course-week {
  width: 100%;
  padding: 1%;
  box-sizing: border-box;

  .week-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 40px;
    padding: 0 1%;

    .btn_wrap {
      width: 200px;
      display: flex;
      justify-content: space-around;
      color: #409eff;

      span {
        cursor: pointer;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 15px;
      }
    }

    .todayDate {
      font-weight: bold;
      font-size: 16px;
    }

    .chooseMonth {
      display: flex;
      justify-content: flex-end;
      width: 18%;

      div {
        flex: 1;
        display: flex;
        padding: 0 2%;
        white-space: nowrap;
        line-height: 20px;
        box-sizing: border-box;

        .square {
          display: flex;
          width: 16px;
          height: 16px;
          border-radius: 4px;
          box-sizing: border-box;
        }

        .title {
          display: flex;
          align-items: center;
          line-height: 16px;
          margin-left: 4px;
          font-size: 14px;
        }

        .in_progress {
          background: #ff6200;
        }

        .has_not_started {
          background: #3291f8;
        }

        .is_expired {
          background: #8e8e93;
        }
      }
    }
  }

  .week_table {
    display: flex;
    flex-direction: column;

    .table_header {
      width: 100%;
      height: 80px;
      background: #eaedf2;
      display: flex;
      flex-direction: column;
      align-items: center;
      border-bottom: 1px solid #eaedf2;
      box-sizing: border-box;

      .table_date,
      .table_week {
        width: 100%;
        height: 40px;
        text-align: left;
        display: flex;
        justify-content: center;
        align-items: center;

        span {
          flex: 1;
          color: #000;
          height: 100%;
          font-size: 14px;
          display: flex;
          justify-content: center;
          align-items: center;
          font-weight: bold;

          .day_item {
            color: #000;
            font-size: 14px;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }

        .first {
          cursor: pointer;

          i {
            margin-left: 1%;
            font-size: 16px;
            font-weight: bold;
          }

          &:hover {
            color: #0d9bf2;
          }

          //border-right: 1px solid #eaedf2;
        }
      }
    }

    .timePeriodList {
      width: 100%;

      .timePeriod_row {
        width: 100%;
        min-height: 60px;

        .timePeriod_col {
          width: 100%;
          min-height: 60px;
          display: flex;

          .timePeriod {
            width: 12.5%;
            display: flex;
            justify-content: center;
            align-items: center;
            border-left: 1px solid #eaedf2;
            border-bottom: 1px solid #eaedf2;
            box-sizing: border-box;
          }

          .row_day {
            width: 87.5%;
            display: flex;
            justify-content: center;
            

            .things:hover {
              background-color: #f0f3f8;
              cursor: pointer;
            }
            .things {
              flex: 1;
              display: flex;
              flex-direction: column;
              align-items: center;
              border-left: 1px solid #eaedf2;
              border-bottom: 1px solid #eaedf2;
              box-sizing: border-box;

              &:last-child {
                border-right: 1px solid #eaedf2;
              }

              .thing_item {
                display: flex;
                font-size: 14px;
                flex-direction: column;
                //justify-content: space-around;
                color: #fff;
                background: #ff6200;
                //min-height: 90px;
                border-radius: 10px;
                margin: 2% 1%;
                padding: 1% 2%;
                cursor: pointer;
                box-sizing: border-box;
              }

              .waiting {
                background: #409eff;
              }

              .outdated {
                color: #fff;
                background: #9cadadb7;
              }
            }
          }
        }
      }
    }
  }
}

.isCurDate {
  color: #ff2525 !important;
}

ul,
li {
  margin: 0;
  padding: 0;
}

.noMore {
  min-height: 200px;
  padding: 2%;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid rgba(156, 173, 173, 0.3);
  color: #9cadadb7;
  box-sizing: border-box;
}
</style>
